﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using JT.WEB.Areas.Identity.Data;
using JT.WEB.Models;
using JTWEB3.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;

namespace JTWEB3.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class RegisterModel : PageModel
    {
        private readonly SignInManager<JTWEB3User> _signInManager;
        private readonly UserManager<JTWEB3User> _userManager;
        private readonly ILogger<RegisterModel> _logger;
        private readonly IEmailSender _emailSender;

        public RegisterModel(
            UserManager<JTWEB3User> userManager,
            SignInManager<JTWEB3User> signInManager,
            ILogger<RegisterModel> logger,
            IEmailSender emailSender)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public string ReturnUrl { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public class InputModel
        {
            [Required(ErrorMessage = "此项必填")]
            //[EmailAddress]
            [Display(Name = "用户名")]
            [RegularExpression(@"[A-Za-z0-9_]{1,20}@[A-Za-z0-9]{2,5}(\.[A-Za-z0-9]{2,5}){1,3}", ErrorMessage = "请输入一个正确的邮箱地址！")]
            //[Remote (action: "VerifyUserAsync", controller: "User")]
            public string Email { get; set; }

            [Required(ErrorMessage = "此项必填")]
            [StringLength(100, ErrorMessage = " {0} 的长度必需不小于 {2}", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "密码")]
            public string Password { get; set; }

            [DataType(DataType.Password)]
            [Display(Name = "确认密码")]
            [Compare("Password", ErrorMessage = "密码与确认密码不匹配")]
            public string ConfirmPassword { get; set; }

            [StringLength(20, ErrorMessage = "呢称长度不能大于10个字.")]
            [RegularExpression(@"^[\u4E00-\u9FA5A-Za-z0-9]+$", ErrorMessage = "呢称由中文、英文、数字组成.")]
            [Display(Name = "呢称")]
            public string NickName { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                JTWEB3User user = new JTWEB3User { UserName = Input.Email, Email = Input.Email, NickName = Input.NickName ?? Input.Email, Password = Input.Password };
                IdentityResult result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    string code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    string callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "确认你的邮件",
                        $"请 <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>点这</a>里确认你的邮件.").ConfigureAwait(false);

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}